//
//  TableViewProtocol.m
//  ElongIpadClient
//
//  Created by zhucuirong on 15/2/11.
//  Copyright (c) 2015年 dragonyuan. All rights reserved.
//

#import "BaseTableViewAdapter.h"

@interface BaseTableViewAdapter ()
@property (nonatomic, copy) TableViewCellConfigureBlock cellConfigureBlock;

@end


@implementation BaseTableViewAdapter

- (instancetype)initWithItems:(NSArray *)items
                 multipleItem:(BOOL)multipleItem
               cellIdentifier:(NSString *)cellIdentifier
           cellConfigureBlock:(TableViewCellConfigureBlock)cellConfigureBlock {
    self = [super init];
    if (self) {
        _items = items;
        _cellIdentifier = cellIdentifier;
        _cellConfigureBlock = [cellConfigureBlock copy];
        _isMultiple=multipleItem;
    }
    return self;
}

- (id)itemAtIndexPath:(NSIndexPath *)indexPath {
    if (_isMultiple) {
        return [[_items objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }
    return [_items objectAtIndex:indexPath.row];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_isMultiple) {
        return [_items count];
    }
    else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView*)tableView
 numberOfRowsInSection:(NSInteger)section {
    if(_isMultiple) {
        return [[_items objectAtIndex:section] count];
    }
    else {
        return [_items count];
    }
}


- (UITableViewCell*)tableView:(UITableView*)tableView
        cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    id cell = [tableView dequeueReusableCellWithIdentifier:_cellIdentifier
                                              forIndexPath:indexPath];
    self.cellConfigureBlock(cell, [self itemAtIndexPath:indexPath], indexPath);
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(tableViewAdapter:didSelectRowAtIndexPath:)]) {
        [self.delegate tableViewAdapter:self didSelectRowAtIndexPath:indexPath];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

#pragma mark - custom accessor 
- (void)setItems:(NSArray *)items {
    if (_items != items) {
        if (_isMultiple && (items && [items isKindOfClass:[NSArray class]] && [items count] > 0) ) {
            NSAssert([items[0] isKindOfClass:[NSArray class]], @"如果有多个section, items必为二维数组");
        }
        _items = items;
    }
}


@end
